package com.ruoyi.system.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.GetOnlineUserCountResult;
import cn.wildfirechat.pojos.GetUserSessionResult;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.pojos.OutputCheckUserOnline;
import cn.wildfirechat.proto.ProtoConstants;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.tools.ShortUUIDGenerator;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.TChatRoomSearchVo;
import com.ruoyi.system.dto.TChatRoomDTO;
import com.ruoyi.system.dto.TChatRoomManagerDTO;
import com.ruoyi.system.mapper.TUserStatusMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TUserMapper;
import com.ruoyi.system.domain.vo.TUserVo;
import com.ruoyi.system.service.ITUserService;

/**
 * app用户Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-18
 */
@Service
@Slf4j
public class TUserServiceImpl implements ITUserService 
{
    @Autowired
    private TUserMapper tUserMapper;

    @Autowired
    private TUserStatusMapper tUserStatusMapper;


    @Autowired
    private ShortUUIDGenerator userNameGenerator;

    /**
     * 查询app用户
     * 
     * @param id app用户主键
     * @return app用户
     */
    @Override
    public TUser selectTUserById(Long id)
    {
        return tUserMapper.selectTUserById(id);
    }

    /**
     * 查询app用户列表
     * 
     * @param tUser app用户
     * @return app用户
     */
    @Override
    public List<TUser> selectTUserList(TUser tUser)
    {
        return tUserMapper.selectTUserList(tUser);
    }

    /**
     * 查询用户VO列表
     * 
     * @param tUser 用户查询条件
     * @return 用户VO集合
     */
    @Override
    public List<TUserVo> selectTUserVoList(TUser tUser)
    {
        List<TUser> userList = tUserMapper.selectTUserList(tUser);
        for (TUser user : userList) {
            try {
                user.setOnline(1);
                IMResult<OutputCheckUserOnline> result = UserAdmin.checkUserOnlineStatus(user.getUid());
                if(result.getResult() != null){
                    List<OutputCheckUserOnline.Session> sessions = result.getResult().getSessions();
                    if (!sessions.isEmpty()){
                        OutputCheckUserOnline.Session session = sessions.get(0);
                        user.setOnline(session.status);
                    }
                }
                // 查询用户session时间
                UserSession userSession = tUserMapper.getUserSession(user.getUid());

                if (userSession != null){
                    if (userSession.getDt()!=null){
                        LocalDateTime ldt =
                            LocalDateTime.ofInstant(Instant.ofEpochMilli(userSession.getDt()), ZoneId.systemDefault());
                        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        user.setLastTime(ldt.format(fmt));
                    }
                    user.setIp(userSession.getIp());
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return userList.stream().map(this::convertToVo).collect(Collectors.toList());
    }

    /**
     * 查询用户数量
     * 
     * @param tUser 用户查询条件
     * @return 用户数量
     */
    @Override
    public int countTUserList(TUser tUser)
    {
        return tUserMapper.countTUserList(tUser);
    }

    /**
     * 将TUser转换为TUserVo
     * 
     * @param tUser 用户实体
     * @return 用户VO
     */
    private TUserVo convertToVo(TUser tUser) {
        TUserVo vo = new TUserVo();
        BeanUtils.copyProperties(tUser, vo);
        // 设置字段映射
//        vo.setUid(tUser.getUid());
//        vo.setName(tUser.getName());
//        vo.setDisplayName(tUser.getDisplayName());
//        vo.setGender(tUser.getGender());
//        vo.setPortrait(tUser.getPortrait());
//        vo.setMobile(tUser.getMobile());
//        vo.setEmail(tUser.getEmail());
//        vo.setAddress(tUser.getAddress());
//        vo.setCompany(tUser.getCompany());
//        vo.setType(tUser.getType());
//        vo.setDt(tUser.getDt());
//        vo.setCreatetime(tUser.getCreatetime());
//        vo.setDeleted(tUser.getDeleted());
//        vo.setUserStatus(tUser.getUserStatus());
        return vo;
    }

    /**
     * 新增app用户
     * 
     * @param tUser app用户
     * @return 结果
     */
    @Override
    public Boolean insertTUser(TUser tUser) throws Exception {
        // 判断用户名是否重复
        boolean usernameAvailable = isUsernameAvailable(tUser.getName());
        if (!usernameAvailable){
            throw new RuntimeException("用户名是否重复");
        }
        InputOutputUserInfo user = new InputOutputUserInfo();
        BeanUtils.copyProperties(tUser,user);
        UserAdmin.createUser(user);
        return true;
    }

    /**
     * 修改app用户
     * 
     * @param tUser app用户
     * @return 结果
     */
    @Override
    public Boolean updateTUser(TUser tUser)
    {
        int updateUserFlag =
            ProtoConstants.UpdateUserInfoMask.Update_User_DisplayName  // 1
                | ProtoConstants.UpdateUserInfoMask.Update_User_Portrait     // 2
                | ProtoConstants.UpdateUserInfoMask.Update_User_Gender       // 4
                | ProtoConstants.UpdateUserInfoMask.Update_User_Mobile       // 8
                | ProtoConstants.UpdateUserInfoMask.Update_User_Email        // 16
                | ProtoConstants.UpdateUserInfoMask.Update_User_Address      // 32
                | ProtoConstants.UpdateUserInfoMask.Update_User_Company      // 64
                | ProtoConstants.UpdateUserInfoMask.Update_User_Social       // 128
                | ProtoConstants.UpdateUserInfoMask.Update_User_Extra        // 256
                | ProtoConstants.UpdateUserInfoMask.Update_User_Name;        // 512
        InputOutputUserInfo user = new InputOutputUserInfo();
        user.setUserId(tUser.getUid());
        BeanUtils.copyProperties(tUser,user);
        try {
            UserAdmin.updateUserInfo(user,updateUserFlag);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return true;
    }

    /**
     * 批量删除app用户
     * 
     * @param ids 需要删除的app用户主键
     * @return 结果
     */
    @Override
    public int deleteTUserByIds(Long[] ids)
    {
        return tUserMapper.deleteTUserByIds(ids);
    }

    /**
     * 删除app用户信息
     * 
     * @param id app用户主键
     * @return 结果
     */
    @Override
    public int deleteTUserById(String id)
    {
        try {
            UserAdmin.destroyUser(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return 1;
    }

    @Override
    public int getCount(int type, LocalDateTime timestamp, LocalDateTime minusTimestamp) {
        return tUserMapper.getCount(type, timestamp,minusTimestamp);
    }

    @Override
    public int getSessionCount() {
        try {
            IMResult<GetOnlineUserCountResult> onlineUserCount = UserAdmin.getOnlineUserCount();
            GetOnlineUserCountResult result = onlineUserCount.getResult();
            int totalOnline = 0;
            for (GetOnlineUserCountResult.Node node : result) {
                totalOnline += node.count;
            }
            return totalOnline;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<TChatRoom> getChatRoomList(TChatRoomSearchVo searchVo) {
        return tUserMapper.getChatRoomList(searchVo);
    }

    @Override
    public TUser selectTUserByUid(String id) {
        return tUserMapper.getByUid(id);

    }

    @Override
    public List<TUserVo> getUserList(List<String> uids) {
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.select("_display_name,_gender,_portrait,_mobile");
        wrapper.in("_uid",uids);
        List<TUser> tUsers = tUserMapper.selectList(wrapper);
        List<TUserVo> tUserVos = new ArrayList<>();
        for (TUser tUser : tUsers) {
            TUserVo tUserVo = new TUserVo();
            BeanUtils.copyProperties(tUser,tUserVo);
            tUserVos.add(tUserVo);
        }
        return tUserVos;
    }

    @Override
    public List<TChatRoomManagerDTO> getListByManager(String roomId) {
        return tUserMapper.getListByManager(roomId);
    }

    @Override
    public List<TUserVo> selectTUserVoListByDisabled(TUser tUser) {
        List<TUserVo> userList = tUserMapper.selectTUserVoListByDisabled(tUser);
        for (TUserVo user : userList) {
            try {
                user.setOnline(1);
                IMResult<OutputCheckUserOnline> result = UserAdmin.checkUserOnlineStatus(user.getUid());
                if(result.getResult() != null){
                    List<OutputCheckUserOnline.Session> sessions = result.getResult().getSessions();
                    if (!sessions.isEmpty()){
                        OutputCheckUserOnline.Session session = sessions.get(0);
                        user.setOnline(session.status);
                    }
                }
                // 查询用户session时间
                UserSession userSession = tUserMapper.getUserSession(user.getUid());

                if (userSession != null){
                    if (userSession.getDt()!=null){
                        LocalDateTime ldt =
                            LocalDateTime.ofInstant(Instant.ofEpochMilli(userSession.getDt()), ZoneId.systemDefault());
                        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        user.setLastTime(ldt.format(fmt));
                    }
                    user.setIp(userSession.getIp());
                }
                if (StringUtils.isNotEmpty(user.getBanTime())){
                    LocalDateTime ldt =
                        LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(user.getBanTime())), ZoneId.systemDefault());
                    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    user.setBanTime(ldt.format(fmt));
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return userList;
    }

    @Override
    public int countTUserVoListByDisabled(TUser tUser) {
        return tUserMapper.countTUserVoListByDisabled(tUser);
    }

    private boolean isUsernameAvailable(String username) {
        try {
            IMResult<InputOutputUserInfo> existUser = UserAdmin.getUserByName(username);
            if (existUser.code == ErrorCode.ERROR_CODE_NOT_EXIST.code) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }



}
